local xingshang = fk.CreateSkill {
  name = "hx__xingshang",
}


xingshang:addEffect("active", {
  anim_type = "support",
  prompt = "#hx__xingshang",
  card_num = 0,
  min_target_num = 0,
  max_target_num = 1,
  interaction = function(self, player)
    local deadPlayers = table.filter(Fk:currentRoom().players, function(p)
      return p.dead
    end)
    local choiceList = {
      "hx__xingshang_restore",
      "hx__xingshang_draw:::" .. math.min(5, math.max(2, #deadPlayers)),
      "hx__xingshang_recover",
      "hx__xingshang_memorialize",
    }
    local choices = {}
    local markValue = player:getMark("@hx__xingshang_song")
    if markValue > 1 then
      table.insertTable(choices, { choiceList[1], choiceList[2] })
    end
    if markValue > 4 then
      table.insert(choices, choiceList[3])
      if table.find(deadPlayers, function(p)
        return p.rest < 1 and not table.contains(Fk:currentRoom():getBanner('memorializedPlayers') or {}, p.id)
      end) then
        local skills = Fk.generals[player.general]:getSkillNameList()
        if player.deputyGeneral ~= "" then
          table.insertTableIfNeed(skills, Fk.generals[player.deputyGeneral]:getSkillNameList())
        end
        if table.find(skills, function(skillName)
          return skillName == xingshang.name
        end) then
          table.insert(choices, "hx__xingshang_memorialize")
        end
      end
    end

    return UI.ComboBox { choices = choices, all_choices = choiceList }
  end,
  times = function(self, player)
    return player.phase == Player.Play and 2 - player:getMark("mou__xingshang_used-phase") or -1
  end,
  can_use = function(self, player)
    return player:usedEffectTimes(self.name, Player.HistoryPhase) < 2 and player:getMark("@hx__xingshang_song") > 1
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, player, to_select, selected, selected_cards)
    if #selected > 0 then
      return false
    end
    if self.interaction.data == "hx__xingshang_recover" then
      return to_select.maxHp < 10
    elseif self.interaction.data == "hx__xingshang_memorialize" then
      return false
    end
    return true
  end,
  feasible = function (self, player, selected, selected_cards, card)
    if self.interaction.data == "hx__xingshang_memorialize" then
      return #selected == 0
    else
      return #selected == 1
    end
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    local target = effect.tos[1]

    local choice = self.interaction.data
    if choice == "hx__xingshang_restore" then
      room:removePlayerMark(player, "@hx__xingshang_song", 2)
      target:reset()
    elseif choice:startsWith("hx__xingshang_draw") then
      room:removePlayerMark(player, "@hx__xingshang_song", 2)
      local deadPlayersNum = #table.filter(room.players, function(p)
        return not p:isAlive()
      end)
      target:drawCards(math.min(5, math.max(2, deadPlayersNum)), xingshang.name)
    elseif choice == "hx__xingshang_recover" then
      room:removePlayerMark(player, "@hx__xingshang_song", 5)
      room:recover({
        who = target,
        num = 1,
        recoverBy = player,
        skillName = xingshang.name,
      })
      if target.dead then return end
      room:changeMaxHp(target, 1)
      if not target.dead and #target.sealedSlots > 0 then
        room:resumePlayerArea(target, {table.random(target.sealedSlots)})
      end
    elseif choice == "hx__xingshang_memorialize" then
      room:removePlayerMark(player, "@hx__xingshang_song", 5)

      local availablePlayers = table.map(table.filter(room.players, function(p)
        return not p:isAlive() and p.rest < 1 and not table.contains(room:getBanner('memorializedPlayers') or {}, p.id)
      end), Util.IdMapper)
      local toId
      local result = room:askToCustomDialog(player, {
        qml_path = "packages/konglong/qml/HX_ZhuiSiBox.qml",
        skill_name = xingshang.name,
        extra_data = { availablePlayers, "$MouXingShang" }
      })

      if result == "" then
        toId = table.random(availablePlayers)
      else
        toId = json.decode(result).playerId
      end

      local to = room:getPlayerById(toId)
      local zhuisiPlayers = room:getBanner("memorializedPlayers") or {}
      table.insertIfNeed(zhuisiPlayers, to.id)
      room:setBanner("memorializedPlayers", zhuisiPlayers)
      local skills = Fk.generals[to.general]:getSkillNameList()
      if to.deputyGeneral ~= "" then
        table.insertTableIfNeed(skills, Fk.generals[to.deputyGeneral]:getSkillNameList())
      end
      skills = table.filter(skills, function(skill_name)
        local skill = Fk.skills[skill_name]
        local attachedKingdom = skill:getSkeleton().attached_kingdom or {}
        return not skill:hasTag(Skill.Lord) and not (#attachedKingdom > 0 and not table.contains(attachedKingdom, player.kingdom))
      end)
      if #skills > 0 then
        room:handleAddLoseSkills(player, table.concat(skills, "|"))
      end

      room:setPlayerMark(player, "@hx__xingshang_memorialized", to.deputyGeneral ~= "" and "seat#" .. to.seat or to.general)
      room:handleAddLoseSkills(player, "-hx__xingshang|-hx__fangzhu|-hx__hx__songwei")
    end
  end,
})

local spec = function (self, event, target, player, data)
  player.room:addPlayerMark(player, "@hx__xingshang_song", math.min(2, 9 - player:getMark("@hx__xingshang_song")))
end

xingshang:addEffect(fk.Damaged, {
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(xingshang.name) and player:getMark("@hx__xingshang_song") < 9 and
      player:usedEffectTimes(self.name) < 1 and data.to:isAlive()
  end,
  on_cost = Util.TrueFunc,
  on_use = spec,
})

xingshang:addEffect(fk.Death, {
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(xingshang.name) and player:getMark("@hx__xingshang_song") < 9
  end,
  on_cost = Util.TrueFunc,
  on_use = spec,
})

xingshang:addLoseEffect(function (self, player, is_death)
  player.room:setPlayerMark(player, "@hx__xingshang_song", 0)
end)

return xingshang
